<?php

namespace App\Http\Controllers;

use App\Http\Model\Api\FinanceWallet;
use App\Http\Model\FormatCheck;
use App\Http\Model\Hint;
use App\Http\Model\OutJson;
use App\Http\Model\User;
use App\Http\Services\ConfigServices;
use App\Http\Services\RegisterServices;

use App\Http\Services\ShareDiamondServices;
use App\Http\Services\ShareSendGoodsServices;
use App\Http\Services\UserServices;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Laravel\Lumen\Routing\Controller as BaseController;
use Illuminate\Http\Request;

class RegisterController extends BaseController
{
    protected $registerServices;
    protected $configServices;
    protected $shareSendGoodsServices;
    protected $shareDiamondServices;
    protected $shareUser;

    public function __construct(ShareDiamondServices $shareDiamondServices, UserServices $userServices, RegisterServices $registerServices, ShareSendGoodsServices $shareSendGoodsServices, ConfigServices $configServices)
    {
        $this->registerServices = $registerServices;
        $this->configServices = $configServices;
        $this->shareSendGoodsServices = $shareSendGoodsServices;
        $this->shareDiamondServices = $shareDiamondServices;
        $this->shareUser = $userServices;
    }


    public function activityRegister(Request $request)
    {
        $phone = $request->post('phone');
        $sms_code = $request->post('code');
        $password = $request->post('password');
        $user_id = $request->post('user_id'); // 主框架 uuid
        if (empty($user_id)) {
            $user_id = 0;
        }
        //邀请用户

        if (!$phone || !FormatCheck::checkPhone($phone)) {
            OutJson::outJsonResult(Hint::PHONE_FORMAT_ERR, []);
        }
        if (!$sms_code || !$password) {
            OutJson::outJsonResult(Hint::PARAM_ERROR, []);
        }

        if (!FormatCheck::checkPassword($password)) {
            OutJson::outJsonResult(Hint::PASSWORD_NOT_ACCORD, []);
        }
        //审核通过 传输register api
        $register = $this->registerServices->send_register($phone, $sms_code, $password, $user_id);
        $success = json_decode($register, true);
        if ($success['code'] != 0 || empty($success)) {
            return $register;
        }
        $new_uid = $success['data']['user_id'];//新用户id

//        $new_uid = 3333;//新用户id

        //判断注册是否过期
        $check_share_date = $this->checkShareDate();
        if (!$check_share_date) {//过期注册
            write_log('register', 'dated', $new_uid);
            OutJson::outJsonResult(Hint::SUCCESS, []);
        }

        //注册成功 绑定用户关系
        $createUser = $this->shareUser->createUser($new_uid, $user_id);
        if (!$createUser) {
            //记录日志
            write_log('register', 'createUserError', $new_uid);
            //api入库失败
            OutJson::outJsonResult(Hint::INVITE_USER_ERROR, []);
        }
        $this->registerServices->clickAwardGoods($new_uid);
//        注册完毕
        OutJson::outJsonResult(Hint::SUCCESS, []);
    }

    /*
         * 发送验证码
         * @param [$phone]   电话
         * */
    public function sendCode(Request $request)
    {
        $data['phone'] = $request->post('phone');
        $data['sms_type'] = $request->post('sms_type');
        if (!$data['phone']) {
            OutJson::outJsonResult(Hint::PHONE_FORMAT_ERR, []);
        }
        $res = curl_request(env('KK_API_HOST') . '/user/sms/code', $data);
////        if($send_api['code'] == 9) {
////            //图形验证码
////            $api = json_decode(curl_request(env('KK_API_HOST') . '/system/captcha_code', ['phone'=>$data['phone']], 'urlencoded', 'GET'), true);
////            OutJson::outJsonResult(Hint::CODE_GIFT_IMG, $api);
////        }
//        if ($send_api['code'] == 0) {
//            OutJson::outJsonResult(Hint::SUCCESS, []);
//        }
       OutJson::outJsonResult(Hint::SUCCESS, $res);
    }

    /**
     * 验证验证码
     */
    public function checkeSmsCode(Request $request) {
        $phone = $request->input('phone');
        $smsCode = $request->input('code');
        return curl_request(env('KK_API_HOST') . '/user/mp_login/check_smscode', [ 'phone' => $phone, 'sms_code' => $smsCode ]);
    }

    /**
     * 获取撩币
     */
    public function getLiaoB(Request $request, FinanceWallet $financeWallet) {
        $user_id = $request->input('user_id');
        $list = $financeWallet->getKkBlance($user_id);
        return OutJson::outJsonResult(Hint::SUCCESS, $list);
    }

    /**
     * 撩币兑换钻石
     */
    public function kkBalanceToDiamond(Request $request) {
        $user_id = $request->input('user_id');
        $kk_balance = $request->input('balance_val');
        $kk_balance *= 10.15; 
        //发送接口请求
        $recharge = [
            'user_id' => $user_id,
            'diamond_num' => $kk_balance,
            'msg' => "兑换活动奖励,获得{$kk_balance}钻",
        ];
        return curl_request(env('KK_API_HOST') . '/finance/diamond/recharge', $recharge);
    }

    public function getUserInfo(Request $request, User $user) {
        $user_id = $request->input('user_id');
        $user_info = $user->getUserInfoByKkaudio($user_id);
        OutJson::outJsonResult(Hint::SUCCESS, $user_info);
    }

    //获取图形
    public function sendGiftCode(Request $request)
    {
        $data['phone'] = $request->post('phone',0);
        //图形验证码
        return json_decode(curl_request(env('KK_API_HOST') . '/system/captcha_code', ['phone' => $data['phone']], 'urlencoded', 'GET'), true);
    }

    //验证图形
    public function checkCaptchaCode(Request $request){
        $data['phone'] = $request->post('phone',0);
        $data['captcha_code'] = $request->post('captcha_code',0);
        //图形验证码
        return  curl_request(env('KK_API_HOST') . '/system/captcha_code/check', $data);
    }


    /*
         * 查看邀请用户
         * @param [$user_id]   查看用户id
         * */
    public function showInviteUser(Request $request)
    {
        $user_id = $request->post('user_id');
        if (!$user_id) {
            OutJson::outJsonResult(Hint::NOT_ALLOWED, []);
        }
        $invite_user_ids = $this->shareUser->myUserInvite($user_id);
        if (!$invite_user_ids)
            OutJson::outJsonResult(Hint::USER_NOT_INVITE, []);
        $all_user = $this->shareUser->getInviteUser($invite_user_ids);
        $data['all_count'] = count($all_user) ?? 0;
        $data['money_user_count'] = $this->shareDiamondServices->getUserMoney($invite_user_ids);
        $data['user_info'] = $all_user;
        OutJson::outJsonNoData(Hint::SUCCESS, $data);
    }

    //获取主框架用户信息
    public function getKkaudioUser(Request $request)
    {
        $user_id = $request->post('user_id');
        if (!$user_id) {
            OutJson::outJsonResult(Hint::NOT_ALLOWED, []);
        }
        $user = $this->shareUser->getKkaudioUserInfo($user_id);
        $data['u_img'] = env('APP_PIC_DOMAIN') . '/album/default.png';
        $data['nickname'] = $user['nickname'] ?? '壳壳用户';
        if (!$user || empty($user['portrait'])) {
            OutJson::outJsonNoData(Hint::SUCCESS, $data);
        }
        $img = json_decode($user['portrait']);
        $data['u_img'] = $img[0];
        if (substr($img[0], 0, 5) != 'http:')
            $data['u_img'] = env('APP_PIC_DOMAIN') . $img[0];

        OutJson::outJsonNoData(Hint::SUCCESS, $data);
    }


    /*
         * 验证活动时间是否截至
         * @param [$phone]   注册电话
         * */
    public function checkShareDate()
    {
        $config_data = $this->configServices->getConfig(1);
        $share_date = explode(' - ', $config_data['share_date']['value']);
        if ($share_date[0] <= date_ymd() && date_ymd() <= $share_date[1]) {
            //活动有效
            return true;
        }
        return false;//活动过期
    }


    /*
        * 获取分享配置
        * */
    public function getShareConfig(Request $request)
    {
        $user_id = $request->post('user_id');
//        if(!$user_id){
//            OutJson::outJsonResult(Hint::NOT_ALLOWED, []);
//        }
        $config_data = $this->configServices->getConfig(1);

        $user = $this->shareUser->getKkaudioUserInfo($user_id);
        $data['u_img'] = env('APP_PIC_DOMAIN') . $config_data['share_kk_portrait']['value']; //获取默认头像
        $data['title'] = $config_data['share_kk_wx_title']['value'];
        $data['desc'] = $config_data['share_kk_wx_desc']['value'];
        $share_date = explode(' - ', $config_data['share_date']['value']);
        $data['share_date'] = substr($share_date[1], 0, 10);
        $data['nickname'] = $user['nickname'] ?? '壳壳用户';

        if (!$user || empty($user['portrait']))
            OutJson::outJsonNoData(Hint::SUCCESS, $data);
        $img = json_decode($user['portrait']);
        $data['u_img'] = $img[0];
        if (substr($img[0], 0, 5) != 'http:')
            $data['u_img'] = env('APP_PIC_DOMAIN') . $img[0];
        OutJson::outJsonNoData(Hint::SUCCESS, $data);
    }
}
